// pages/alarm-submit/alarm-submit.js
const app = getApp()
const api = require('../../utils/api.js')
const authManager = require('../../utils/auth.js')

Page({
  data: {
    // 报警类型列表
    alarmTypes: [],
    selectedType: '',
    selectedTypeIndex: -1,
    
    // 报警级别
    alarmLevels: [
      { label: '低级', value: 'low', color: '#52c41a' },
      { label: '中级', value: 'medium', color: '#faad14' },
      { label: '高级', value: 'high', color: '#ff4d4f' },
      { label: '紧急', value: 'critical', color: '#f5222d' }
    ],
    selectedLevel: 'medium',
    selectedLevelIndex: 1,
    
    // 位置信息
    location: {
      latitude: 0,
      longitude: 0,
      accuracy: 0,
      address: '获取中...'
    },
    locationLoading: false,
    
    // 描述信息
    description: '',
    
    // 证据文件
    evidenceFiles: [],
    uploadLoading: false,
    
    // 提交状态
    submitting: false,
    
    // 紧急联系人
    emergencyContacts: [],
    
    // 表单验证
    errors: {}
  },

  onLoad(options) {
    console.log('报警提交页面加载')
    
    // 检查登录状态
    if (!authManager.requireLogin()) {
      return
    }
    
    // 检查身份绑定
    if (!authManager.requireBind()) {
      return
    }
    
    // 初始化数据
    this.initData()
    
    // 如果是紧急报警
    if (options.emergency === 'true') {
      this.setData({
        selectedLevel: 'critical',
        selectedLevelIndex: 3
      })
    }
  },

  onShow() {
    // 获取当前位置
    this.getCurrentLocation()
  },

  /**
   * 初始化数据
   */
  async initData() {
    try {
      // 并行获取数据
      const [typesResult, contactsResult, permissionResult] = await Promise.all([
        this.loadAlarmTypes(),
        this.loadEmergencyContacts(),
        this.checkSubmitPermission()
      ])
      
      console.log('初始化数据完成')
    } catch (error) {
      console.error('初始化数据失败:', error)
      wx.showToast({
        title: '加载数据失败',
        icon: 'error'
      })
    }
  },

  /**
   * 加载报警类型
   */
  async loadAlarmTypes() {
    try {
      const result = await api.alarm.getTypes()
      
      if (result.code === 200) {
        const alarmTypes = result.data || []
        this.setData({ alarmTypes })
        
        // 如果有类型，默认选择第一个
        if (alarmTypes.length > 0) {
          this.setData({
            selectedType: alarmTypes[0].value,
            selectedTypeIndex: 0
          })
        }
      }
      
      return result
    } catch (error) {
      console.error('获取报警类型失败:', error)
      throw error
    }
  },

  /**
   * 加载紧急联系人
   */
  async loadEmergencyContacts() {
    try {
      const schoolInfo = authManager.getSchoolInfo()
      if (!schoolInfo || !schoolInfo.schoolId) {
        return
      }
      
      const result = await api.alarm.getEmergencyContact(schoolInfo.schoolId)
      
      if (result.code === 200) {
        this.setData({
          emergencyContacts: result.data || []
        })
      }
      
      return result
    } catch (error) {
      console.error('获取紧急联系人失败:', error)
      throw error
    }
  },

  /**
   * 检查提交权限
   */
  async checkSubmitPermission() {
    try {
      const userInfo = authManager.userInfo
      const result = await api.alarm.checkSubmitPermission({
        userId: userInfo.userId,
        type: this.data.selectedType
      })
      
      if (result.code !== 200) {
        wx.showModal({
          title: '权限不足',
          content: result.message || '您暂无报警提交权限',
          showCancel: false,
          success: () => {
            wx.navigateBack()
          }
        })
      }
      
      return result
    } catch (error) {
      console.error('检查提交权限失败:', error)
      throw error
    }
  },

  /**
   * 获取当前位置
   */
  getCurrentLocation() {
    this.setData({ locationLoading: true })
    
    wx.getLocation({
      type: 'gcj02',
      altitude: true,
      success: (res) => {
        console.log('获取位置成功:', res)
        
        this.setData({
          location: {
            latitude: res.latitude,
            longitude: res.longitude,
            accuracy: res.accuracy,
            address: '位置获取成功'
          },
          locationLoading: false
        })
        
        // 逆地理编码获取地址
        this.reverseGeocode(res.latitude, res.longitude)
      },
      fail: (error) => {
        console.error('获取位置失败:', error)
        
        this.setData({
          location: {
            ...this.data.location,
            address: '位置获取失败'
          },
          locationLoading: false
        })
        
        wx.showToast({
          title: '获取位置失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 逆地理编码
   */
  reverseGeocode(latitude, longitude) {
    // 这里可以调用地图API进行逆地理编码
    // 暂时使用模拟地址
    const mockAddress = `模拟地址 经度:${longitude.toFixed(6)} 纬度:${latitude.toFixed(6)}`
    
    this.setData({
      location: {
        ...this.data.location,
        address: mockAddress
      }
    })
  },

  /**
   * 选择报警类型
   */
  onTypeChange(e) {
    const index = e.detail.value
    const alarmTypes = this.data.alarmTypes
    
    this.setData({
      selectedTypeIndex: index,
      selectedType: alarmTypes[index].value
    })
  },

  /**
   * 选择报警级别
   */
  onLevelChange(e) {
    const index = e.detail.value
    const alarmLevels = this.data.alarmLevels
    
    this.setData({
      selectedLevelIndex: index,
      selectedLevel: alarmLevels[index].value
    })
  },

  /**
   * 描述输入
   */
  onDescriptionInput(e) {
    this.setData({
      description: e.detail.value
    })
  },

  /**
   * 选择证据文件
   */
  chooseEvidence() {
    wx.showActionSheet({
      itemList: ['拍照', '从相册选择', '录音', '录像'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            this.takePhoto()
            break
          case 1:
            this.chooseImage()
            break
          case 2:
            this.recordAudio()
            break
          case 3:
            this.recordVideo()
            break
        }
      }
    })
  },

  /**
   * 拍照
   */
  takePhoto() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['camera'],
      success: (res) => {
        this.addEvidenceFile({
          type: 'image',
          path: res.tempFiles[0].tempFilePath,
          size: res.tempFiles[0].size,
          name: `photo_${Date.now()}.jpg`
        })
      }
    })
  },

  /**
   * 选择图片
   */
  chooseImage() {
    wx.chooseMedia({
      count: 3,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        res.tempFiles.forEach((file, index) => {
          this.addEvidenceFile({
            type: 'image',
            path: file.tempFilePath,
            size: file.size,
            name: `image_${Date.now()}_${index}.jpg`
          })
        })
      }
    })
  },

  /**
   * 录音
   */
  recordAudio() {
    const recorderManager = wx.getRecorderManager()
    
    wx.showModal({
      title: '开始录音',
      content: '点击确定开始录音，录音完成后会自动停止',
      success: (res) => {
        if (res.confirm) {
          // 开始录音
          recorderManager.start({
            duration: 60000, // 最长60秒
            sampleRate: 16000,
            numberOfChannels: 1,
            encodeBitRate: 96000,
            format: 'mp3'
          })
          
          wx.showToast({
            title: '开始录音',
            icon: 'none'
          })
          
          // 录音结束回调
          recorderManager.onStop((res) => {
            console.log('录音结束:', res)
            
            this.addEvidenceFile({
              type: 'audio',
              path: res.tempFilePath,
              size: res.fileSize,
              duration: res.duration,
              name: `audio_${Date.now()}.mp3`
            })
          })
          
          // 10秒后自动停止录音
          setTimeout(() => {
            recorderManager.stop()
            wx.showToast({
              title: '录音完成',
              icon: 'success'
            })
          }, 10000)
        }
      }
    })
  },

  /**
   * 录像
   */
  recordVideo() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['video'],
      sourceType: ['camera'],
      maxDuration: 30, // 最长30秒
      success: (res) => {
        this.addEvidenceFile({
          type: 'video',
          path: res.tempFiles[0].tempFilePath,
          size: res.tempFiles[0].size,
          duration: res.tempFiles[0].duration,
          name: `video_${Date.now()}.mp4`
        })
      }
    })
  },

  /**
   * 添加证据文件
   */
  addEvidenceFile(file) {
    const evidenceFiles = [...this.data.evidenceFiles, file]
    this.setData({ evidenceFiles })
    
    wx.showToast({
      title: '添加成功',
      icon: 'success'
    })
  },

  /**
   * 删除证据文件
   */
  removeEvidence(e) {
    const index = e.currentTarget.dataset.index
    const evidenceFiles = this.data.evidenceFiles
    evidenceFiles.splice(index, 1)
    
    this.setData({ evidenceFiles })
  },

  /**
   * 预览证据文件
   */
  previewEvidence(e) {
    const index = e.currentTarget.dataset.index
    const file = this.data.evidenceFiles[index]
    
    if (file.type === 'image') {
      wx.previewImage({
        current: file.path,
        urls: [file.path]
      })
    } else if (file.type === 'video') {
      wx.previewMedia({
        sources: [{
          url: file.path,
          type: 'video'
        }]
      })
    } else if (file.type === 'audio') {
      // 播放音频
      const audioContext = wx.createInnerAudioContext()
      audioContext.src = file.path
      audioContext.play()
    }
  },

  /**
   * 验证表单
   */
  validateForm() {
    const errors = {}
    
    // 验证报警类型
    if (!this.data.selectedType) {
      errors.type = '请选择报警类型'
    }
    
    // 验证描述
    if (!this.data.description.trim()) {
      errors.description = '请输入事件描述'
    } else if (this.data.description.length < 10) {
      errors.description = '事件描述不能少于10个字符'
    }
    
    // 验证位置
    if (!this.data.location.latitude || !this.data.location.longitude) {
      errors.location = '请获取当前位置'
    }
    
    this.setData({ errors })
    
    return Object.keys(errors).length === 0
  },

  /**
   * 提交报警
   */
  async submitAlarm() {
    // 表单验证
    if (!this.validateForm()) {
      wx.showToast({
        title: '请完善报警信息',
        icon: 'error'
      })
      return
    }
    
    this.setData({ submitting: true })
    
    try {
      // 构建报警数据
      const alarmData = {
        type: this.data.selectedType,
        level: this.data.selectedLevel,
        description: this.data.description,
        location: {
          latitude: this.data.location.latitude,
          longitude: this.data.location.longitude,
          accuracy: this.data.location.accuracy,
          address: this.data.location.address
        },
        timestamp: Date.now(),
        source: 'manual', // 手动报警
        deviceInfo: {
          platform: 'miniprogram',
          version: wx.getSystemInfoSync().version
        }
      }
      
      // 如果有证据文件，先上传
      if (this.data.evidenceFiles.length > 0) {
        const uploadResult = await this.uploadEvidenceFiles()
        if (uploadResult.success) {
          alarmData.evidence = uploadResult.files
        }
      }
      
      // 提交报警
      const result = await api.alarm.submit(alarmData)
      
      if (result.code === 200) {
        wx.showToast({
          title: '报警提交成功',
          icon: 'success'
        })
        
        // 跳转到报警详情页
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/alarm-detail/alarm-detail?id=${result.data.alarmId}`
          })
        }, 1500)
      } else {
        throw new Error(result.message || '提交失败')
      }
    } catch (error) {
      console.error('提交报警失败:', error)
      
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'error'
      })
    } finally {
      this.setData({ submitting: false })
    }
  },

  /**
   * 上传证据文件
   */
  async uploadEvidenceFiles() {
    this.setData({ uploadLoading: true })
    
    try {
      const files = this.data.evidenceFiles.map(file => ({
        filePath: file.path,
        type: file.type,
        name: file.name
      }))
      
      const result = await api.alarm.uploadBatch(files, {
        alarmType: this.data.selectedType
      })
      
      return {
        success: true,
        files: result.data
      }
    } catch (error) {
      console.error('上传证据文件失败:', error)
      
      wx.showToast({
        title: '文件上传失败',
        icon: 'error'
      })
      
      return {
        success: false,
        error: error.message
      }
    } finally {
      this.setData({ uploadLoading: false })
    }
  },

  /**
   * 呼叫紧急联系人
   */
  callEmergency(e) {
    const index = e.currentTarget.dataset.index
    const contact = this.data.emergencyContacts[index]
    
    wx.showModal({
      title: '拨打电话',
      content: `确定要拨打 ${contact.name}: ${contact.phone} 吗？`,
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: contact.phone
          })
        }
      }
    })
  },

  /**
   * 返回首页
   */
  goHome() {
    wx.switchTab({
      url: '/pages/home/home'
    })
  }
}) 